package Search;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import DataTags.DataTagsAdapter;
import DataTags.files;
import System.Classifier;
import com.cloudgarden.resource.SWTResourceManager;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.FileDialog;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class guiSearch extends Search {
	/**
	 * @author oz
	 */
/**
 * Notice:
 * 	When you enter a word to the search text box ,
 *  if this word is a tag ,enter it and mark the find files radio button ,then press the search button.
 *  (this will search for you all the files with this tag).
 *  if this word is a file , enter it and mark the find tags radio button, then press the search button. 
 *  (this will search for you all the tags of this file). 	
 *  
 *  
 *  
 *  When you have searched for the file with this tags ,and chose one from the combo box of the result,
 *  a new dialog will be opened to you, there you can tag the file according to the classifying algorithm you previously chose,
 *  or to delete this file and all of its tags from the DB.
 *  
 */
	
/**
 * this is the Gui search constrctor
 * @param DataTagsAdapter Tags
 */
	public guiSearch(DataTagsAdapter Tags) {
		super(Tags);
		//createSShell();
		
	}

	private Shell sShell = null;
	private Text text = null;
	private Button button = null;
	//private Combo combo=null;
	private boolean weSearchFor;
	private Button button1;

	/**
	 * This method initializes sShell
	 */
	private void createSShell() {
		
		sShell = new Shell(Display.getDefault(),0);

		{
			//Register as a resource user - SWTResourceManager will
			//handle the obtaining and disposing of resources
			SWTResourceManager.registerResourceUser(sShell);
		}
		File f = new File("");
		String go=new String(f.getAbsolutePath());
		Image bg=new Image(Display.getDefault(),go+"/1488184-xs.jpg");
		sShell.setText("Search");
		//sShell.setSize(190, 197);
		sShell.setBounds(215, 317, 190, 197);
		sShell.setLayout(null);
		sShell.setBackgroundImage(bg);
		text = new Text(sShell, SWT.BORDER);
		text.setBounds(10, 60, 163, 20);
		final String []allFiles=this.getAllFiles();
		final  String []allTags=this.getAllTags();
		//final FileDialog dialog;
		final Button btnFiles = new Button(sShell, SWT.RADIO);
		btnFiles.setBounds(10, 106, 61, 22);
		btnFiles.setText("find tags");

	    final Combo combo = new Combo(sShell, SWT.NONE);
	    combo.setBounds(10, 33, 163, 20);
	    button = new Button(sShell, SWT.NONE);
	    button.setBounds(102, 80, 71, 23);
	    button.setText("Search");
	    button.setBackgroundImage(bg);
	    {
	    	button1 = new Button(sShell, SWT.PUSH | SWT.CENTER);
	    	button1.setText("Open");
	    	button1.setBounds(10, 80, 71, 23);
	    	button1.setBackgroundImage(bg);
	    	button1.addSelectionListener(new SelectionAdapter() {
	    		public void widgetSelected(SelectionEvent evt) {
	    			button1WidgetSelected(evt);
	    		}
	    	});
	    }

	    Button btnAllTags = new Button(sShell, SWT.RADIO);
	    btnAllTags.setBounds(120, 10, 52, 22);
	    btnAllTags.addSelectionListener(new SelectionAdapter() {
	        public void widgetSelected(SelectionEvent arg0) {
	        	combo.removeAll();
	        	//allTags=Search.this.getAllTags();
	        	sShell.redraw();
	        	for(int i=0;i<allTags.length;i++){
	        		combo.add(allTags[i]);
	        	}
	        	
	        }
	    });
	    btnAllTags.setText("All tags");

	    Button btnAllFiles = new Button(sShell, SWT.RADIO);
	    btnAllFiles.setBounds(10, 10, 51, 22);
	    btnAllFiles.addSelectionListener(new SelectionAdapter() {
	    
	    	public void widgetSelected(SelectionEvent arg0) {
	    		combo.removeAll();
	    		for(int i=0;i<allFiles.length;i++){
	    			combo.add(allFiles[i]);
	    		}
	    	}
	    });
	    btnAllFiles.setText("All files");

	    Button btnTags = new Button(sShell, SWT.RADIO);
	    btnTags.setBounds(116, 106, 56, 22);
	    btnTags.setText("find files");

	    final Combo comboRes = new Combo(sShell, SWT.NONE);
	    comboRes.setBounds(10, 130, 163, 20);
	    button.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
	    	public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
	    		System.out.println("Searching for "+text.getText()); 
	    		comboRes.removeAll();
	    		String searchItem = text.getText();
	    		searchItem.trim();
	    		if(!searchItem.isEmpty()){
	    			weSearchFor=false;
	    			weSearchFor=btnFiles.getSelection();//searchItem=fileName,we are looking for its tags
	    			String st=searchThis(searchItem,weSearchFor);
	    			if(!st.isEmpty()){
	    				String[]myFoundTags=st.split("@");
	    				comboRes.removeAll();
	    				for(int i=0;i<myFoundTags.length;i++){
	    					comboRes.add(myFoundTags[i]);
	    				}
	    			
	  	    				
	    			}	
	    			else{
	    				
	    					MessageBox messageBox = 
	    					new MessageBox(sShell, SWT.OK);
	    					messageBox.setMessage("Sorry , your searchItem have not found.Try different searchItem or use regex");
	    					messageBox.open();
	    					
	    					
	    				}
	    		}
	    		else{
	    			MessageBox messageBox = 
  					new MessageBox(sShell, SWT.OK);
	    			messageBox.setMessage("Please enter a file/tag to search");
	    			messageBox.open();
  					
	    		}
	    		
	    		
	    	}
	    });
	    comboRes.addSelectionListener(new SelectionAdapter(){
	    	public void widgetSelected(SelectionEvent arg0){
	    		if (!weSearchFor){
	    			String[] st;
	    			String s="";
	    			int index=comboRes.getSelectionIndex();
		    		if (index!=-1){
		    			 String str=comboRes.getItem(index);
		    			 st=str.split("	");
		    			 //text.setText(st);
		    			 s=st[2];/* the path*/
		    		}
	    			FileDialog fd = new FileDialog(sShell, SWT.OPEN);/* we need to open the path of this file*/
	    			fd.setText("Open files");
	    			fd.setFilterPath(s);
	    			String[] filterExt = { "*.txt","*.*" };
	    			fd.setFilterExtensions(filterExt);
	    			String selected = fd.open();/*here we need to exec the selected file*/
	    			if(selected !=null){
	    				/*
	    				 * if you choose a file you can tag it 
	    				 */
	    				Classifier clasi=new Classifier();;
	    				MessageBox messageBox = 
	      					new MessageBox(sShell, SWT.YES|SWT.NO);
	    	    			messageBox.setMessage("Do you want to tag this file?");
	    	    			if (messageBox.open()==SWT.YES){
	    	    				//InputDialog inp=new InputDialog(new Shell() ,"","Enter the tags for your selected file , [space -between tags]",null,null);      
	    	    				 /*inp.getValue().trim().split(" ");*/   
	    	    				try {
									clasi.insertTagToFile(clasi.getTags(new File(selected)), new File(selected));
								} catch (Exception e) {}
	    	    				
	    	    			}
	    	    			else{
	    	    				messageBox.setMessage("Do you want to delete the tags from this file?");
	    	    				if (messageBox.open()==SWT.YES){
	    	    					clasi.deleteTagToFile(new File(selected));
	    	    				}
	    	    			}
	    			}
	    			
	    			}
	    		}
	    	});
	    combo.addSelectionListener(new SelectionAdapter() {
	    	public void widgetSelected(SelectionEvent arg0) {
	    		int index=combo.getSelectionIndex();
	    		if (index!=-1){
	    			String st=combo.getItem(index);
	    			text.setText(st);
	    		}
	    	}
	    });
	   
	}

	/**
	 * opens the shell
	 */
	public void Open(){
        if((sShell==null)||(sShell.isDisposed())){
        	createSShell();
        	sShell.open();
        }
        else{
			//sShell.close();
			sShell.dispose();
		}
		
	}
	
	@SuppressWarnings("unchecked")
	private void button1WidgetSelected(SelectionEvent evt) {
		String target=text.getText();
		if (target.equals("")) {
			return;
		}
		String q=
			"select t "+
			"from  files t "+
			"where (t.name like :rep1)";
		SessionFactory sessionQFactory = new Configuration().configure().buildSessionFactory();
		if(sessionQFactory!=null)
		{
			System.out.println("sessionFactory  work");
		}
		Session session = sessionQFactory.openSession();
		if(session!=null){
			System.out.println("session work");
		}
		Query qeQuery=session.createQuery(q).setParameter("rep1",target);
		List<files> myTags=qeQuery.list();
		//remove the file name an extention
		String res=new String(myTags.get(0).getPath());
		res=res.replace('\\','@');
		String[] parts=res.split("@");
		res=res.replaceAll(parts[parts.length-1],"");
		res=res.replace('@', '\\');
		try {
			Runtime.getRuntime().exec("explorer.exe "+res);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
